package org.bookie.mtest.framework;

import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;

import java.io.IOException;

import org.xml.sax.SAXException;

import com.meterware.httpunit.SubmitButton;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebResponse;

/**
 * Wrapper around HTTP {@link WebForm}
 * 
 * @author zubairov
 *
 */
public class Form {

	private WebForm wf;
	private Page page;

	/**
	 * Constructor
	 * @param form
	 */
	public Form(WebForm form, Page parent) {
		this.wf = form;
		this.page = parent;
	}

	
	/**
	 * Sets a field in the form
	 * 
	 * @param fieldName
	 *            name of the field (not ID)
	 * @param fieldValue
	 *            value of the field
	 * @throws SAXException
	 */
	public void setField(String fieldName, String fieldValue)
			throws SAXException {
		wf.setParameter(fieldName, fieldValue);
	}

	/**
	 * Triggers action on given page by action button ID
	 * 
	 * @param string
	 *            NAME(!) of the button
	 * @throws SAXException
	 * @throws IOException
	 */
	public void submit(String name) throws IOException, SAXException {
		SubmitButton button = wf.getSubmitButton(name);
		assertNotNull(button, page.msg("Can't find button with ID=" + name));
		WebResponse response = wf.submit(button);
		page.responseChanged(response);
	}
	
	/**
	 * Submits this form using the web client from which it was originally obtained.
	 * @throws SAXException
	 * @throws IOException
	 */
	public void submit() throws IOException, SAXException {
		WebResponse response = wf.submit();
		page.responseChanged(response);
	}
	
	/**
	 * Asserts that a form field is present
	 * @param name name of the field
	 */
	public void assertHasParameterNamed(String name){
		assertTrue(wf.hasParameterNamed(name));
	}
}
